/*
 * Copyright 2008-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.faxsun.controller.account;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.domain.OrderItem;
import org.broadleafcommerce.core.order.service.type.OrderStatus;
import org.broadleafcommerce.core.pricing.service.exception.PricingException;
import org.broadleafcommerce.core.web.controller.account.BroadleafOrderHistoryController;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.faxsun.core.order.domain.FSOrderImpl;
import com.faxsun.core.order.domain.FSOrderItemImpl;
import com.faxsun.core.order.service.FSOrderService;
import com.faxsun.core.order.service.type.FSInternalOrderStatus;
import com.faxsun.core.order.service.type.FSOrderStatus;
import com.faxsun.web.processor.tool.CheckMobile;

@Controller
@RequestMapping("/account/orders")
public class OrderHistoryController extends BroadleafOrderHistoryController {

	@Resource(name = "blOrderService")
	FSOrderService fsOrderService;

	@RequestMapping(method = RequestMethod.GET)
	public String viewOrderHistory(HttpServletRequest request, Model model) {
		List<Order> orders = orderService.findOrdersForCustomer(CustomerState.getCustomer(),
				OrderStatus.SUBMITTED);
		orders.addAll(orderService.findOrdersForCustomer(CustomerState.getCustomer(), FSOrderStatus.CONFIRMED));
		orders.addAll(orderService.findOrdersForCustomer(CustomerState.getCustomer(), FSOrderStatus.DELIVERY));
		orders.addAll(orderService.findOrdersForCustomer(CustomerState.getCustomer(), FSOrderStatus.SINGED));
		orders.addAll(orderService.findOrdersForCustomer(CustomerState.getCustomer(), FSOrderStatus.CANCELLED));
		Collections.sort(orders, new Comparator<Order>() {

			@Override
			public int compare(Order order1, Order order2) {
				return order2.getSubmitDate().compareTo(order1.getSubmitDate());
			}

		});
		model.addAttribute("orders", orders);
		model.addAttribute("isMobile", CheckMobile.check(request.getHeader("user-agent")));
		return getOrderHistoryView();
	}

	@RequestMapping(value = "/{orderNumber}", method = RequestMethod.GET)
	public String viewOrderDetails(HttpServletRequest request, Model model,
			@PathVariable("orderNumber") String orderNumber) {
		model.addAttribute("isMobile", CheckMobile.check(request.getHeader("user-agent")));
		return super.viewOrderDetails(request, model, orderNumber);
	}

	@RequestMapping(value = "/{orderNumber}/{itemNumber}", method = RequestMethod.GET)
	public String refundOrderItem(HttpServletRequest request, Model model,
			@PathVariable("orderNumber") String orderNumber, @PathVariable("itemNumber") String itemNumber) {

		FSOrderImpl order = (FSOrderImpl) orderService.findOrderByOrderNumber(orderNumber);
		if (order != null && order.getStatus().equals(FSOrderStatus.SINGED)) {
			// order exists and order has been collected
			order.setInternalStatus(FSInternalOrderStatus.REFUND_REQUEST);

			List<OrderItem> orderItems = order.getOrderItems();

			for (OrderItem item : orderItems) {
				if (item.getId().toString().equals(itemNumber)) {
					FSOrderItemImpl orderItem = (FSOrderItemImpl) item;
					orderItem.setStatus(FSInternalOrderStatus.REFUND_REQUEST.getType());
					try {
						orderService.save(order, false);
						break;
					} catch (PricingException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return super.viewOrderDetails(request, model, orderNumber);
	}

	@RequestMapping(value = "/shippments/{itemId}", method = RequestMethod.GET)
	public String viewShippmentDetails(HttpServletRequest request, Model model,
			@PathVariable("itemId") String itemId) {

		OrderItem item = fsOrderService.readOrderItem(itemId);
		model.addAttribute("orderItem", item);
		return "account/partials/shippmentDetails";
	}
}
